import React, { Component } from 'react';
import { NavBar, Icon, WingBlank, List, Toast } from 'antd-mobile';
import styles from './index.less';
import router from 'umi/router';
import MyNavBar from 'components/navbar';
import ErrorMsg from 'components/form-error-msg/index';
import { InputItem, Switch, Stepper, Range, Button } from 'antd-mobile';
import { createForm } from 'rc-form';
import { idCardRegular } from 'utils/regular';
import { connect } from 'dva';
import { returnUrl as url } from 'utils/ip';
import { getIsDingTalk, isDingTalk, backToOut, checkAlipay } from 'utils/utils'
import commonStyles from 'utils/common.less';
import { ALIPAY_MODE, AUTHENTICATION_FAIL_CODE, PROCESS_STATUS, ENTER_TYPE } from 'utils/Enum';

@connect(({ PersonalCertificationModel, pdfModel }) => ({ PersonalCertificationModel, pdfModel }))
class enterpriseCertificationAlipayDetail extends Component {
	constructor(props) {
		super(props);
		this.state = {
			btnDisabled: false,
			errorIDCard: false
		}
	}

	isSuccessChange = () => {
		let isSuccess = localStorage.getItem('isSuccess') || '';
		const nextUrl = localStorage.getItem('nextUrl') || '';
		const isDingTalk = getIsDingTalk();
		if (isSuccess !== '') {
			window.removeEventListener('storage', this.isSuccessChange)
			console.log('进入支付宝页面的监听事件')
			console.log('监听页面的nextUrl:', nextUrl)
			console.log('监听页面的nextUrl-type', typeof nextUrl)
			if (nextUrl === '' || nextUrl === 'undefined') {
				//从外部进入就跳转回去
				backToOut();
			}
			else if (nextUrl) {
				router.push(nextUrl)
			}
			localStorage.setItem('bizNo', '');
			localStorage.setItem('Certification', '');
			localStorage.setItem('status', '');
			localStorage.setItem('isSuccess', '')
			localStorage.setItem('Contact', '');
			localStorage.setItem('Captcha', '');
			localStorage.setItem('nextUrl', '');
			if (isDingTalk === 'true') {
				localStorage.setItem('haveToAlipay', '')
			}
		}
	}

	startListen = async () => {
		Toast.loading('跳转中', 1)
		window.addEventListener("storage", this.isSuccessChange)
	}

	getInputValue = () => {
		const { form: { validateFields } } = this.props;
		setTimeout(() => {
			validateFields((error, values) => {
				if (!error) {
					this.setState({
						btnDisabled: true
					})
				} else {
					this.setState({
						btnDisabled: false
					})
				}
			});
		})
	}

	InputIDChange = (e) => {
		if (!idCardRegular.reg.test(e) && e) {
			this.setState({
				errorIDCard: true
			})
		} else {
			this.setState({
				errorIDCard: false
			})
		}
		this.getInputValue()
	}
	//页面跳转
	goNext = (e) => {
		// const isDingTalk=localStorage.getItem('isDingTalk');
		if (isDingTalk()) {
			this.startListen();
		}
		const { dispatch, location: { query: { type, Certification } } } = this.props
		const userWsid = localStorage.getItem('userWsid') || ''
		const session = localStorage.getItem("Session") || ''
		const returnUrl = localStorage.getItem('returnUrl') || ''
		const enterType = localStorage.getItem('enterType') || ''
		const envelopeWsid = localStorage.getItem('envelopeWsid') ? localStorage.getItem('envelopeWsid') : ''
		const participantWsid = localStorage.getItem('participantWsid') ? localStorage.getItem('participantWsid') : ''
		const haveToAlipay = 'yes'
		this.props.form.validateFields((error, values) => {
			let alipayReturnUrl = ''
			switch (type) {
				case AUTHENTICATION_FAIL_CODE.EUSR:
				case AUTHENTICATION_FAIL_CODE.PUSR:
					alipayReturnUrl = `${url()}/Authentication?envelopeWsid=${envelopeWsid}&participantWsid=${participantWsid}&type=${type}&userWsid=${userWsid}&session=${session}&Certification=${Certification}&returnUrl=${escape(returnUrl)}&enterType=${enterType}&haveToAlipay=${haveToAlipay}`
					break
				case AUTHENTICATION_FAIL_CODE.EPUSR:
					alipayReturnUrl = `${url()}/SignCertificationResults?envelopeWsid=${envelopeWsid}&participantWsid=${participantWsid}&type=${type}&userWsid=${userWsid}&session=${session}&Certification=${Certification}&returnUrl=${escape(returnUrl)}&enterType=${enterType}&haveToAlipay=${haveToAlipay}`
					break
				default:
					break
			}
			if (isDingTalk()) {
				alipayReturnUrl = `dingtalk://dingtalkclient/page/link?url=${escape(alipayReturnUrl)}`;
			}
			this.setState({
				errorIDCard: false
			})
			dispatch({
				type: 'PersonalCertificationAlipayModel/postAlipayVerification',
				payload: {
					...values,
					idttvType: ALIPAY_MODE.MULTIPLE_FACTOR,
					userPersonWsid: userWsid,
					returnUrl: alipayReturnUrl,
				},
				callback: (state, zhimaCertificateUrl) => {
					if (state === 'success') {
						// console.log('zhimaCetificateUrl',zhimaCertificateUrl)
						// checkAlipay(`alipays://platformapi/startapp?appId=20000067&url=${escape(zhimaCertificateUrl)}`)
						window.location.href = `alipays://platformapi/startapp?appId=20000067&url=${escape(zhimaCertificateUrl)}`
					}
					else {
						let urlNext = ''
						switch (type) {
							case AUTHENTICATION_FAIL_CODE.EUSR:
								urlNext = '/Authentication?status=' + PROCESS_STATUS.EPUSR_AUTHORIZING_ERROR
								break;
							case AUTHENTICATION_FAIL_CODE.PUSR:
								urlNext = '/Authentication?status=' + PROCESS_STATUS.PUSR_AUTHORIZING_ERROR
								break
							case AUTHENTICATION_FAIL_CODE.EPUSR:
								urlNext = '/Authentication?status=' + PROCESS_STATUS.PUSR_AUTHORIZING_ERROR
								break
							default:
								break
								router.push(urlNext)
						}
					}
				}
			})
		});
	};
	render() {
		const isDingTalk = getIsDingTalk();
		const { btnDisabled, errorIDCard } = this.state;
		const Item = List.Item;
		const Brief = Item.Brief;
		const { getFieldDecorator } = this.props.form;
		const { location: { query: { type, url, Certification } } } = this.props
		// const contentContainer=' '+commonStyles.headerTop
		const contentContainer = isDingTalk === 'true' ? '' : ' ' + commonStyles.headerTop
		return (
			<div className={styles.baseLayout}>
				<MyNavBar title={"支付宝认证"} backUrl={`/PersonalCertification?url=${url}&type=${type}&Certification=${Certification}`} />
				<form className={styles.infoForm + contentContainer}>
					<List className={styles.formList}>
						{getFieldDecorator('certName', {
							initialValue: '',
							rules: [
								{
									required: true,
									message: '标题内容必填！',
								},
							],
						})(
							<InputItem clear placeholder="填写真实姓名" ref={el => (this.autoFocusInst = el)} onChange={this.getInputValue}>
								真实姓名
                			</InputItem>
						)}
						{getFieldDecorator('certNo', {
							initialValue: '',
							rules: [
								{
									required: true,
									message: '标题内容必填！',
									pattern: idCardRegular.reg,
								},
							],
						})(
							<InputItem clear placeholder="填写身份证号" ref={el => (this.autoFocusInst = el)} onChange={this.InputIDChange}>
								身份证号
                			</InputItem>
						)}
						{errorIDCard && <ErrorMsg errorMsg='身份证填写错误' />}
					</List>
				</form>

				<div className={styles.footerContainer}>
					<Button type="primary" shape="round"
						disabled={!btnDisabled}
						onClick={this.goNext.bind(this)}>
						下一步
          			</Button>
				</div>


			</div>
		)
	}
}

export default createForm()(enterpriseCertificationAlipayDetail);
